package com.newasia.cashier.Shiro;

import com.newasia.user.ISysMenuService;
import com.newasia.user.ISysRoleService;
import com.newasia.user.ISysUserService;
import com.newasia.user.dto.SysMenuDto;
import com.newasia.user.dto.SysRoleDto;
import com.newasia.user.dto.SysUserLoginResponse;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Description Shiro权限匹配和账号密码匹配
 * @Author Sans
 * @CreateTime 2019/6/15 11:27
 */
public class ShiroRealm extends AuthorizingRealm {

    @Reference(timeout = 3000)
    ISysUserService sysUserService;
    @Reference(timeout = 3000)
    ISysRoleService sysRoleService;
    @Reference(timeout = 3000)
    ISysMenuService sysMenuService;

    /**
     * 授权权限
     * 用户进行权限验证时候Shiro会去缓存中找,如果查不到数据,会执行这个方法去查权限,并放入缓存中
     * @Author Sans
     * @CreateTime 2019/6/12 11:44
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取用户ID
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        SysUserLoginResponse loginResponse = (SysUserLoginResponse) principalCollection.getPrimaryPrincipal();
        Long userId =loginResponse.getUserId();
        //这里可以进行授权和处理
        Set<String> rolesSet = new HashSet<>();
        Set<String> permsSet = new HashSet<>();
        //查询角色和权限(这里根据业务自行查询)
        List<SysRoleDto> sysRoleDtoList = sysRoleService.selectSysRoleByUserId(userId);
        for (SysRoleDto sysRoleDto:sysRoleDtoList) {
            rolesSet.add(sysRoleDto.getRoleName());
            List<SysMenuDto> sysMenuDtoList = sysMenuService.selectSysMenuByRoleId(sysRoleDto.getRoleId());
            for (SysMenuDto sysMenuDto :sysMenuDtoList) {
                permsSet.add(sysMenuDto.getPerms());
            }
        }
        //将查到的权限和角色分别传入authorizationInfo中
        authorizationInfo.setStringPermissions(permsSet);
        authorizationInfo.setRoles(rolesSet);
        return authorizationInfo;
    }

    /**
     * 身份认证
     * @Author Sans
     * @CreateTime 2019/6/12 12:36
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取用户的输入的账号.
        return null;
    }
}
